package com.bdult.vh.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.bdult.vh.common.CommonUtil;
import com.bdult.vh.common.UtilBean;
import com.bdult.vh.service.BoardService;
import com.bdult.vh.service.ItemService;
import com.bdult.vh.service.MemberService;
import com.bdult.vh.service.OrderService;
import com.bdult.vh.service.CommonService;
import com.bdult.vh.vo.BoardVO;

/**
 * Handles requests for the application home page.
 */
@Controller
public class MypageController {
	
	private static final Logger logger = LoggerFactory.getLogger(MypageController.class);
	
	@Autowired
	private ItemService itemService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private BoardService boardService;
	
	@Autowired
	private CommonService commonService;
	
	@RequestMapping(value="qna_list")
	public ModelAndView qna_list(Model model, @RequestParam Map<String, Object> paramMap) {
		
		ModelAndView mv = new ModelAndView();
		
		mv.setViewName("qna_list");
		return mv;
	}
	
	@RequestMapping(value="wishlist_guest")
	public ModelAndView wishlist_guest(Model model, @RequestParam Map<String, Object> paramMap) {
		
		ModelAndView mv = new ModelAndView();
		
		mv.setViewName("wishlist_guest");
		return mv;
	}
	
	@RequestMapping(value="wishlist")
	public ModelAndView wishlist(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		
		//DB에서 장바구니 상품리스트를 뽑아온다
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		paramMap.put("cstmno", Long.valueOf(cstmno).longValue());
		
		HashMap<String,Object> wishList = new HashMap<String,Object>();
		wishList = orderService.getWishList(cstmno);
	System.out.println("wishList = " + wishList);
		String cart_list = "[]";
		if(wishList != null ) {
			cart_list = (String)wishList.get("WISHLIST");
		}
		System.out.println("cart_list = " + cart_list);
		
		JSONArray jsonArray = JSONArray.fromObject(cart_list);
		System.out.println("jsonArray = " + jsonArray.size());
		
		ArrayList<HashMap<String, Object>> itemList_temp = new ArrayList<HashMap<String,Object>>();
		for(int i=0; i<jsonArray.size();i++) {
			JSONObject jSonObject = (JSONObject) jsonArray.get(i);
			String aa = (String) jSonObject.get("a");
			String aaa[] = aa.split("_");
			
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("prdcd", aaa[0]);
			map.put("sapcd", aaa[1]);
			map.put("buyqty", jSonObject.get("b"));
			
			itemList_temp.add( map );
		}		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("prdlist", itemList_temp);
		
		//장바구니 상품리스트로 상품정보를 가져온다. 
		int totalCnt = 0;
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		System.out.println("map = " + map + " / " + map.get("prdlist") );
		
		if(! map.get("prdlist").toString().equals("[]") ) {		
			itemList = itemService.getItemList_prdlist(map);
			System.out.println("-- itemList = " + itemList);
			for(HashMap<String,String> item : itemList) {
				//이미지 가져오기
				String prdimg1 = item.get("PRDIMG1");
				prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
				item.put("PRDIMG1_ENC", prdimg1);
				
				//옵션 가져오기
				String sapcd = "";
				String lmtordcnt = "";
				ArrayList<HashMap<String,String>> optList = itemService.getItemOption(item.get("PRDCD"));
				System.out.println("opt = " + optList);
				
				if(optList != null ) {
					if(optList.size() > 0 ) {
						HashMap<String,String> opt = optList.get(0);
						sapcd = opt.get("SAPCD");
						lmtordcnt = String.valueOf( opt.get("LMTORDCNT") );
						
					}
				}
				item.put("SAPCD", sapcd);
				item.put("LMTORDCNT", lmtordcnt);
			}
		}
		
		mv.addObject("itemList", itemList);
		
		mv.setViewName("wishlist");
		return mv;
	}
	
	@RequestMapping(value="mypage/mypage")
	public ModelAndView mypage(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		
		Map<String, Object> uMap = new HashMap<String, Object>();
		uMap.put("CSTMNO", cstmno);
		Map<String, Object> pointInfo = memberService.getMemberPoint(uMap);
		
		int iCouponTotal = 0;
		if(request.getSession().getAttribute("cstmno") != null) {
			HashMap<String, Object> pMap = new HashMap<String, Object>();
			pMap.put("cstmno", Long.valueOf(cstmno).longValue());
			pMap.put("prdcd", "");
			
			HashMap<String, Object> couponTT = new HashMap<String, Object>();
			couponTT = orderService.getCouponTotal(cstmno);
			iCouponTotal = Integer.parseInt( couponTT.get("COUPONCNT").toString() );
		}
		
		mv.addObject("pointInfo", pointInfo);
		mv.addObject("couponTotal", iCouponTotal);
		mv.setViewName("mypage/mypage");
		return mv;
	}
	
	@RequestMapping(value="mypage/account")
	public ModelAndView account(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		
		Map<String, Object> uMap = new HashMap<String, Object>();
		uMap.put("CSTMNO", cstmno);
		Map<String, Object> pointInfo = memberService.getMemberPoint(uMap);
		
		ArrayList<HashMap<String, Object>> couponList = null;
		int iCouponTotal = 0;
		if(request.getSession().getAttribute("cstmno") != null) {
			HashMap<String, Object> pMap = new HashMap<String, Object>();
			pMap.put("cstmno", Long.valueOf(cstmno).longValue());
			pMap.put("prdcd", "");
			
			couponList = orderService.getCouponList(pMap);
			
			HashMap<String, Object> couponTT = new HashMap<String, Object>();
			couponTT = orderService.getCouponTotal(cstmno);
			iCouponTotal = Integer.parseInt( couponTT.get("COUPONCNT").toString() );
		}
		
		mv.addObject("pointInfo", pointInfo);
		mv.addObject("couponList", couponList);
		mv.addObject("couponTotal", iCouponTotal);
		mv.setViewName("mypage/account");
		return mv;
	}
	
	@RequestMapping(value="orderinfo")
	public ModelAndView orderinfo(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		ArrayList<HashMap<String, Object>> myOrderList = orderService.myOrderList(cstmno);
		ArrayList<HashMap<String, String>> itemOptList = itemService.getItemOption(myOrderList.get(0).get("PRDCD").toString());
		int cnt = myOrderList.size();
		
		mv.addObject("itemoption", itemOptList);
		mv.addObject("myOrderList", myOrderList);
		mv.addObject("cnt", cnt);
		
		
		mv.setViewName("orderinfo");
		return mv;
	}
	
	
	@RequestMapping(value="orderinfo_detail")
	public ModelAndView orderinfo_detail(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		String ordno = request.getParameter("ordno");
		
		HashMap<String, String> orderinfoDetail = orderService.selectOrderComplete(ordno);
		//ArrayList<HashMap<String, String>> itemOptList = itemService.getItemOption(orderinfoDetail.get(31).toString());
		
		mv.addObject("orderinfoView", orderinfoDetail);
		mv.addObject("pdtnmb", orderinfoDetail.get(31));
		//mv.addObject("itemoption", itemOptList);
		
		mv.setViewName("orderinfo_detail");
		return mv;
	}
	
	
	@RequestMapping(value="orderinfo_cancel")
	public ModelAndView orderinfo_cancel(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		String ORDNO = request.getParameter("ordno");

		ArrayList<HashMap<String, String>> selectCodeList = commonService.selectCodeList("AR");
		mv.addObject("selectCodeList", selectCodeList);
		mv.addObject("ordno", ORDNO);
		HashMap<String, Object> oMap = new HashMap<String, Object>();
		oMap.put("CSTMNO", Long.valueOf(cstmno).longValue());
		oMap.put("ORDNO", ORDNO);
		ArrayList<HashMap<String, Object>> getMyOrderSingle = orderService.getMyOrderSingle(oMap);
		mv.addObject("getMyOrderSingle", getMyOrderSingle);
		
		String sSttlMethod = (String) getMyOrderSingle.get(0).get("STTLMETHOD");
		String sCurordstatcd = (String) getMyOrderSingle.get(0).get("CURORDSTATCD");
		String sDpstCl = (String) getMyOrderSingle.get(0).get("DPSTCL");
		
		
		String getAccNoYn = orderService.getAccNoYn(ORDNO);
		HashMap<String, Object> getApprvCancelPrc = orderService.getApprvCancelPrc(ORDNO);

		String sStrSttlMethod = "";
		String sStrRePrc = "";
		
		if(sSttlMethod.equals("SM01")){
			sStrSttlMethod = "결제 취소";
		}else if(sSttlMethod.equals("SM02")){
			sStrSttlMethod = "결제 시 등록한 계좌로 자동 환불";
		}else if(sSttlMethod.equals("SM03")&&sCurordstatcd.equals("OD01")){
			sStrSttlMethod = "무통장입금 즉시취소";
		}else if(sSttlMethod.equals("SM03")&&sCurordstatcd.equals("OD02")){
			sStrSttlMethod = "하단입력 계좌로 환불(3일이내)";
		}else if(sSttlMethod.equals("SM04")){
			sStrSttlMethod = "하단입력 계좌로 환불(3일이내)";
		}else if(sSttlMethod.equals("SM05")&&sCurordstatcd.equals("OD01")){
			sStrSttlMethod = "가상계좌 즉시취소";
		}else if(sSttlMethod.equals("SM05")&&sCurordstatcd.equals("OD02")){
			sStrSttlMethod = "가상계좌취소 (환불)";
		}   
		
//		mv.addObject("getAccNoYn",getAccNoYn);
		mv.addObject("sStrSttlMethod",sStrSttlMethod);
		mv.addObject("apprvCancelPrc",getApprvCancelPrc);
		
		mv.setViewName("orderinfo_cancel");
		return mv;
	}
	
	
	@RequestMapping(value="orderinfo_cancelproc")
	public ModelAndView orderinfo_cancelproc(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		String ordno = request.getParameter("ordno");
		
		mv.setViewName("orderinfo_cancelproc");
		return mv;
	}
	
	
	@RequestMapping(value="mypage/qna_write", method = RequestMethod.GET)
	public ModelAndView qna_write(Model model, 
			@RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		String odrno = request.getParameter("ordno");
		//logger.info("=======]odrno[============{}", odrno);
		String boardTypeId = "8";
		HashMap<String, Object> orderinfoDetail = orderService.getOrderSingle(odrno);
		HashMap<String, Object> boardType= boardService.getboardTypeDetail(boardTypeId);
		mv.addObject("orderinfoDetail", orderinfoDetail);
		mv.addObject("boardType", boardType);
		
		mv.setViewName("mypage/qna_write");
		return mv;
	}
	@RequestMapping(value="mypage/qna_write", method = RequestMethod.POST)
	public ModelAndView qna_write_proc(Model model, 
			@RequestParam Map<String, Object> paramMap, 
			@ModelAttribute("board") BoardVO board,
			HttpSession session,
			HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		BigDecimal member_id =  (BigDecimal) session.getAttribute("cstmno");
		String remoteAddress = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
			       .getRequest().getRemoteAddr();
		logger.info("=============] member_id [============ {}", member_id);
		logger.info("=============] remoteAddress [============ {}", remoteAddress);
		//boardtypeid
		//boardid
		//boardtitle
		board.setBoardpassword("AA0iBY3PDwjYo");
		
		
		board.setBoardisopenyn("Y");
		board.setBoardisdelyn("N");
		board.setBoardisnoticeyn("N");
		board.setBoardvisitcount("0");
		board.setBoardcreateip(remoteAddress);
		board.setBoardstate("N");
		board.setBoardorder(1);
		board.setBoarddepth("1");
		//board.setCreatedon();
		board.setCreatedby(member_id);
		boardService.insertBoard(board);
		mv.setViewName("redirect:/orderinfo.vh");
		return mv;
	}
}
